using System;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;


namespace LoD.WPClientLibrary.Helper {
    public static class JsonHelper {
        public static string Serialize<T>(T obj) {
            var serializer = new DataContractJsonSerializer(obj.GetType());
            var ms = new MemoryStream();
            serializer.WriteObject(ms, obj);
            string retVal = Encoding.UTF8.GetString(ms.ToArray(), 0, (int)ms.Length);
            ms.Dispose();
            return retVal;
        }

        public static T Deserialize<T>(string json) where T : class {
            var obj = Activator.CreateInstance<T>();
            var ms = new MemoryStream(Encoding.UTF8.GetBytes(json));
            var serializer = new DataContractJsonSerializer(obj.GetType());
            obj = serializer.ReadObject(ms) as T;
            ms.Close();
            ms.Dispose();
            return obj;
        }
    }
}